import React from 'react'
import { Modal, Input, Icon } from 'antd'
import { deepFullCopy } from "share/common";
const InputSearch = Input.Search;
import "styles/financial-account/view-info.scss"

class ChooseInfo extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      data: props.infoData,
      searchValue: '',
      showData: props.infoData,
      chooseData: {}
    }
  }

  componentWillReceiveProps = nextProps => {
    this.setState({ showData: nextProps.infoData, data: nextProps.infoData });
  };

  handleCancel = () => {
    const { onCancel } = this.props;
    this.setState({searchValue: ''});
    onCancel();
  };

  handleSearch = value => {
    const { data } = this.state;
    if(value){
      this.setState({showData: data.filter(item => ~item.segmentCode.indexOf(value))})
    } else {
      this.setState({showData: deepFullCopy(data)})
    }
  };

  handleOnOk = () => {
    const { chooseData } = this.state, { onOk } = this.props;
    onOk(chooseData);
  };

  handleChoose = item => {
    this.setState({ chooseData: this.getFormatData(item) });
  };

  getFormatData = item => {
    const { format } = this.props;
    let res = {};
    Object.keys(format).map(key => {
      res[key] = item[key];
    });
    return res;
  };

  render(){
    const { showData, chooseData } = this.state;
    const { title, visible } = this.props;
    return(
      <Modal visible={visible}
             onOk={this.handleOnOk}
             onCancel={this.handleCancel}
             width={500}
             className={'view-info'}
             title={title}>
        <InputSearch onChange={e => this.handleSearch(e.target.value)} style={{marginBottom: '10px'}}/>
        <div className={'content-body'}>
          {
            showData.map(item => {
              return <div className={`block-view ${chooseData.id === item.id ? 'selected' : ''}`} onClick={() => this.handleChoose(item)}>
                <div className="title-view">{item.segmentName}</div>
                <span style={{lineHeight:'20px'}}>{item.segmentCode}</span>
                {chooseData.id === item.id && <Icon type="check" className="searcher-list-item-check"/>}
              </div>
            })
          }
        </div>
      </Modal>
    )
  }
}

ChooseInfo.propTypes = {
  visible: React.PropTypes.bool,
  infoData: React.PropTypes.array,
  onCancel: React.PropTypes.func,
  title: React.PropTypes.string,
  onOk: React.PropTypes.func,
  format: React.PropTypes.object
};

export default ChooseInfo;
